﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Budget.MthCategoryWCFProxy;
using Budget.CategoryWCFProxy;
using Newtonsoft.Json;
using System.IO;
using System.ServiceModel;
using Budget.HelperClasses;
using Budget.SpendingWCFProxy;
using Budget.MthWCFProxy;

namespace Budget.Data
{
	public partial class MthCategories : System.Web.UI.Page
	{
		private int mthid = 0;

		protected void Page_Load( object sender, EventArgs e )
		{
			string action = Request.Params["xaction"];
			if ( !string.IsNullOrEmpty( action ) )
			{
				switch ( action )
				{
					case "batchupdate":
						BatchUpdate();
						break;
					case "list":
						ListCategories();
						break;
					default:
						ListMonthCategories();
						break;
				}
			}
		}

		private void BatchUpdate()
		{
			StreamReader inputDataStream = new StreamReader( Request.InputStream );
			string data = inputDataStream.ReadToEnd();
			List<DisplayMthCategory> objData = JsonConvert.DeserializeObject<List<DisplayMthCategory>>( data );

			int mthid = objData.First().MthId;

			foreach ( DisplayMthCategory dmc in objData )
			{
				// do we insert or update
				if ( dmc.MthCategoryId == 0 && !dmc.InitiallySet && dmc.FinallySet )
				{
					//insert
					Budget.MthCategoryWCFProxy.MthCategory mc = new Budget.MthCategoryWCFProxy.MthCategory()
					{
						MthId = dmc.MthId,
						CategoryId = dmc.CategoryId,
						BudgetAmount = dmc.BudgetAmount,
						BaseAmount = dmc.BaseBudgetAmount,
						Timestamp = DateTime.Now
					};

					WCFHelper.Using<MthCategoryServiceClient>( svc => svc.Save( mc ) );
				}
				else if ( dmc.MthCategoryId > 0 && dmc.FinallySet )
				{
					Budget.MthCategoryWCFProxy.MthCategory mc = null;
					WCFHelper.Using<MthCategoryServiceClient>( svc => mc = svc.GetByMthCategoryId( dmc.MthCategoryId ) );
					if ( mc != null )
					{
						mc.BudgetAmount = dmc.BudgetAmount;
					}
					WCFHelper.Using<MthCategoryServiceClient>( svc => svc.Save( mc ) );
				}
				else if ( dmc.MthCategoryId > 0 && dmc.InitiallySet && !dmc.FinallySet )
				{
					WCFHelper.Using<MthCategoryServiceClient>( svc => svc.Delete( dmc.MthCategoryId ) );
				}
			}

			this.mthid = mthid;

			ListCategories();
		}

		private void ListCategories()
		{
			int mthId = 1;
			if ( !string.IsNullOrEmpty( Request.Params["mthId"] ) )
			{
				mthId = Convert.ToInt32( Request.Params["mthId"] );
			}
			else
			{
				StreamReader inputDataStream = new StreamReader( Request.InputStream );
				string data = inputDataStream.ReadToEnd();
				if ( data.Length > 0 )
				{
					mthId = JsonConvert.DeserializeObject<int>( data );
				}
				else
				{
					//if we've reached this point it can be assumed that ListCategories() hasn't been called direct from the UI
					mthId = this.mthid;
				}
			}

			JsonResponse<DisplayMthCategory> response = new JsonResponse<DisplayMthCategory>();

			if ( mthId == 0 )
			{
				response.Data = null;
				response.Count = 0;
				response.Success = true;
				response.Message = "There were no month selected.";
			}
			else
			{
				MthCategoryWCFProxy.MthCategory[] mthCategories = new MthCategoryWCFProxy.MthCategory[0];
				WCFHelper.Using<MthCategoryServiceClient>( svc => mthCategories = svc.GetByMonth( mthId ) );

				DisplayMthCategory[] dmcs = ( from mc in mthCategories
											  select new DisplayMthCategory()
											  {
												  MthCategoryId = mc.MthCategoryId,
												  CategoryId = mc.CategoryId
											  } ).ToArray();

				foreach ( var item in dmcs )
				{
					WCFHelper.Using<CategoryServiceClient>( svc => item.CategoryName = svc.GetCategoryById( item.CategoryId ).CategoryName );
				}

				response.Data = dmcs;
				response.Count = dmcs.Count();
				response.Success = true;
				response.Message = "Successfully retrieved all Mth Category objects.";
			}

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}

		private void ListMonthCategories()
		{
			int mthId = 1;
			if ( !string.IsNullOrEmpty( Request.Params["mthId"] ) )
			{
				mthId = Convert.ToInt32( Request.Params["mthId"] );
			}


			JsonResponse<DisplayMthCategory> response = new JsonResponse<DisplayMthCategory>();

			if ( mthId == 0 )
			{
				response.Data = null;
				response.Count = 0;
				response.Success = true;
				response.Message = "There were no month selected.";
			}
			else
			{
				MthCategoryWCFProxy.MthCategory[] mthCategories = new MthCategoryWCFProxy.MthCategory[0];
				WCFHelper.Using<MthCategoryServiceClient>( svc => mthCategories = svc.GetByMonth( mthId ) );

				Category[] categories = new Category[0];
				WCFHelper.Using<CategoryServiceClient>( svc => categories = svc.GetAll() );

				Mth previousMonth = null;
				WCFHelper.Using<MthServiceClient>( svc => previousMonth = svc.GetPreviousMonth( mthId ) );

				List<MonthSummary> previousMonthSummary = new List<MonthSummary>();
				if ( previousMonth != null )
				{
					WCFHelper.Using<SpendingServiceClient>( svc => previousMonthSummary = svc.GetMonthCategorySummary( new DateTime( previousMonth.Year, previousMonth.Month, 1 ) ).ToList() );
				}

				DisplayMthCategory[] dmcs = ( from c in categories
											  select new DisplayMthCategory()
											  {
												  MthId = mthId,
												  CategoryId = c.CategoryId,
												  CategoryName = c.CategoryName,
												  BaseBudgetAmount = ( ( from mc in mthCategories
																		 where mc.CategoryId == c.CategoryId
																		 select mc.BaseAmount ).SingleOrDefault() > 0 ? ( from mc in mthCategories
																														  where mc.CategoryId == c.CategoryId
																														  select mc.BaseAmount ).SingleOrDefault() : c.BudgetAmount ),
												  BudgetAmount = ( ( from mc in mthCategories
																	 where mc.CategoryId == c.CategoryId
																	 select mc.BudgetAmount ).SingleOrDefault() ),
												  CarriedOverBudget = ( ( from pms in previousMonthSummary
																		  where pms.CategoryId == c.CategoryId
																		  select pms.BudgetAmount - pms.AmountSpent ).SingleOrDefault() ),
												  InitiallySet = ( ( from mc in mthCategories
																	 where mc.MthId == mthId && mc.CategoryId == c.CategoryId
																	 select mc ).Count() > 0 ? true : false ),
												  FinallySet = ( ( from mc in mthCategories
																   where mc.MthId == mthId && mc.CategoryId == c.CategoryId
																   select mc ).Count() > 0 ? true : false ),
												  MthCategoryId = ( ( from mc in mthCategories
																	  where mc.MthId == mthId && mc.CategoryId == c.CategoryId
																	  select mc.MthCategoryId ).SingleOrDefault() )
											  } ).ToArray();


				foreach ( var dmc in dmcs )
				{
					WCFHelper.Using<SpendingServiceClient>( svc => dmc.HasSpendings = svc.SpendingsExistForMonth( dmc.MthId ) );
				}

				response.Data = dmcs;
				response.Count = dmcs.Count();
				response.Success = true;
				response.Message = "Successfully retrieved all Mth Category objects.";
			}

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}
	}
}
